/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package cn.anlaser.utils;

import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang3.StringUtils;

import com.google.common.collect.Maps;

public class SearchFilter {

	public enum Operator {
		EQ, LIKE, GT, LT, GTE, LTE, ISNULL, NOTNULL
	}

	public String fieldName;
	public Object value;
	public Operator operator;

	/**
	 * @param fieldName 包含操作符，默认无时为EQ 例如 name=name:EQ
	 * @param value
	 */
	public SearchFilter(String fieldName, Object value) {
		this.fieldName = fieldName;
		this.value = value;
	}
	/**
	 * ISNULL
	 * @param fieldName
	 * @param operator
	 */
	public SearchFilter(String fieldName, Operator operator) {
		this.fieldName = fieldName;
		this.operator = operator;
	}
	public SearchFilter(String fieldName, Operator operator, Object value) {
		this.fieldName = fieldName;
		this.value = value;
		this.operator = operator;
	}

	/**
	 * searchParams中key的格式为OPERATOR_FIELDNAME
	 */
	public static Map<String, SearchFilter> parse(
			Map<String, Object> searchParams) {
		Map<String, SearchFilter> filters = Maps.newHashMap();

		for (Entry<String, Object> entry : searchParams.entrySet()) {
			// 过滤掉空值
			String key = entry.getKey();
			Object value = entry.getValue();
			String strVal="";
			if(!value.getClass().equals(String.class)){
				strVal=value.toString();
			}
			if (StringUtils.isBlank(strVal)) {
				continue;
			}

			// 拆分operator与filedAttribute
			String[] names = StringUtils.split(key, "_");
			if (names.length != 2) {
				throw new IllegalArgumentException(key
						+ " is not a valid search filter name,must [name_"+Operator.EQ+"]");
			}
			String filedName = names[1];
			Operator operator = Operator.valueOf(names[0]);

			// 创建searchFilter
			SearchFilter filter = new SearchFilter(filedName, operator, value);
			filters.put(key, filter);
		}

		return filters;
	}
}
